package com.testjpa.service;

import com.testjpa.entity.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者: LCG
 * 日期: 2020/5/25 16:18
 * 描述:
 */

@Component
public class JpaEntityService {

    @Autowired
    private EntityManager entityManager;


    public Map<String,Object> toPage(String userName,String createDate){


        StringBuilder stringBuilder=new StringBuilder("select ju.* from jpa_user ju where 1=1");

        StringBuilder countsql=new StringBuilder("select count(ju.id) from jpa_user ju where 1=1");

        if(userName!=null&&!userName.equals("")){
            stringBuilder.append(" and ju.user_name=");
            stringBuilder.append("'"+userName+"'");

            countsql.append(" and ju.user_name=");
            countsql.append("'"+userName+"'");
        }
        if(createDate!=null&&!createDate.equals("")){
            stringBuilder.append(" and ju.createDate=");
            stringBuilder.append("'"+createDate+"'");

            countsql.append(" and ju.createDate=");
            countsql.append("'"+createDate+"'");
        }


        //添加分页的关键字
        stringBuilder.append(" limit ");
        stringBuilder.append(" 0,");//表示第一页
        stringBuilder.append("1");//表示每页有多少条

        System.out.println(stringBuilder.toString());

        //查询分页的列表
        Query nativeQuery = entityManager.createNativeQuery(stringBuilder.toString(), MyUser.class);

        List resultList = nativeQuery.getResultList();

        //查询总数据量
        Query nativeQuery1 = entityManager.createNativeQuery(countsql.toString());

        Object singleResult = nativeQuery1.getSingleResult();

        Map<String,Object> resultMap=new HashMap<String,Object>();
        resultMap.put("pageList",resultList);
        resultMap.put("totals",singleResult);

        return resultMap;
    }


}
